<template>
  <div class="app-container">
    <div class="table-tools">
      <div>
        <el-button :icon="Plus" type="primary" @click="showDialog">
          新增
        </el-button>
        <el-button :icon="Delete" @click="deletes">删除</el-button>
      </div>
      <div class="search">
        <el-input
          v-model="search.searchData"
          style="max-width: 20rem"
          placeholder="请输入搜索内容"
          clearable
        >
          <template #prepend>
            <el-select
              v-model="search.searchType"
              placeholder="搜索类型"
              style="width: 100px"
            >
              <el-option label="用户ID" :value="searchType.id" />
              <el-option label="用户名" :value="searchType.userName" />
              <el-option label="真实姓名" :value="searchType.realName" />
              <el-option label="用户性别" :value="searchType.sex" />
              <el-option label="用户积分" :value="searchType.grade" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="searchClick(search)" />
          </template>
        </el-input>
      </div>
    </div>
    <el-table ref="tableRef" :data="usersData">
      <el-table-column type="selection" align="center" width="60px" />
      <el-table-column
        prop="id"
        label="用户ID"
        align="center"
        width="90px"
        sortable
      />
      <el-table-column label="用户头像" align="center" width="120px" sortable>
        <template #default="scope">
          <el-avatar style="background: #04c9be" :src="scope.row.picture">
            {{ scope.row.realName.charAt(0) }}
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        label="用户名"
        align="center"
        sortable
        :sort-method="userNameSort"
      >
        <template #default="scope">
          <div>{{ scope.row.userName }}</div>
          <!-- <div v-if="!scope.row.editStatus">{{ scope.row.userName }}</div>
          <div v-else>
            <el-input v-model="scope.row.editData.userName" />
          </div> -->
        </template>
      </el-table-column>
      <el-table-column
        label="真实姓名"
        align="center"
        sortable
        :sort-method="realNameSort"
      >
        <template #default="scope">
          <div v-if="!scope.row.editStatus">
            {{ scope.row.realName }}
          </div>
          <div v-else>
            <el-input v-model="scope.row.editData.realName" />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="用户性别"
        align="center"
        sortable
        :sort-method="sexSort"
      >
        <template #default="scope">
          <div v-if="!scope.row.editStatus">
            {{
              scope.row.gender === 0
                ? "未知"
                : scope.row.gender === 1
                  ? "男"
                  : "女"
            }}
          </div>
          <div v-else>
            <el-select
              v-model="scope.row.editData.gender"
              placeholder="搜索类型"
              style="width: 100px"
            >
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
              <el-option label="未知" :value="0" />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="grade" label="用户积分" align="center" sortable>
        <template #default="scope">
          <div v-if="!scope.row.editStatus">{{ scope.row.grade }}</div>
          <div v-else>
            <el-input-number v-model="scope.row.editData.grade" />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="是否管理员"
        align="center"
        sortable
        :sort-method="AdminSort"
      >
        <template #default="scope">
          <div v-if="!scope.row.editStatus">
            <el-switch
              :active-value="1"
              :inactive-value="2"
              v-model="scope.row.isAdmin"
              disabled
            />
          </div>
          <div v-else>
            <el-switch
              :active-value="1"
              :inactive-value="2"
              v-model="scope.row.editData.isAdmin"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="160px">
        <template #default="scope">
          <el-button @click="editClick(scope.row)">
            {{ scope.row.editStatus ? "保存" : "编辑" }}
          </el-button>
          <el-button
            v-if="scope.row.editStatus"
            @click="CancelClick(scope.row)"
          >
            取消
          </el-button>
          <el-button v-else @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        layout="prev, pager, next, total"
        :pager-count="5"
        :total="pageParam.total"
        :default-page-size="pageParam.pageSize"
        v-model:current-page="pageParam.page"
        background
        @current-change="pageChange"
      />
    </div>
    <addUser ref="addUserDialog" @on-close="getUsers()" />
  </div>
</template>

<script setup lang="ts">
import { TableInstance } from "element-plus";
import { Search, Delete, Plus } from "@element-plus/icons-vue";
import addUser from "./components/add-user.vue";
import UserAPI, { type User, UsersData } from "@/api/user";
import { Sort } from "@/utils";

interface Edit {
  editData?: User;
  editStatus?: boolean;
}

defineOptions({
  name: "User",
});

const pageParam = ref<PageQuery & pageCount>({
  page: 1,
  pageSize: 10,
  total: 0,
});

//用户数据
const usersData = ref<(User & Edit)[]>([]);
const updateUsers = ({ total, rows }: PageResult<(User & Edit)[]>) => {
  pageParam.value.total = total;
  usersData.value = rows as (User & Edit)[];
  usersData.value.forEach((value, key) => {
    usersData.value[key].editData = Object.assign({}, value);
    usersData.value[key].editStatus = false;
  });
};
const getUsers = async (params?: UsersData & PageQuery) => {
  updateUsers(await UserAPI.getUsers({ ...params, ...pageParam.value }));
};

//表格列排序功能
const sexSort = (a: User, b: User) => Sort(a.gender, b.gender);
const AdminSort = (a: User, b: User) => Sort(a.isAdmin, b.isAdmin);
const realNameSort = (a: User, b: User) => Sort(a.realName, b.realName);
const userNameSort = (a: User, b: User) => Sort(a.userName, b.userName);

//新增用户弹窗功能
const addUserDialog = ref<InstanceType<typeof addUser>>();
const showDialog = () => addUserDialog.value?.closeClick();

//编辑用户功能
const editClick = async (data: User & Edit) => {
  if (data.editStatus) {
    await UserAPI.editUser(data.editData as User);
    ElMessage.success("编辑用户成功");
    getUsers();
  }
  CancelClick(data);
};
const CancelClick = (data: User & Edit) => (data.editStatus = !data.editStatus);

//删除功能
const deleteClick = async ({ id }: User & Edit, message: boolean = true) => {
  await UserAPI.deleteUser({ id });
  if (message === true) {
    getUsers();
    ElMessage.success("删除用户成功");
  }
};

//批量删除功能
const tableRef = ref<TableInstance>();
const deletes = () => {
  const rows: Array<User> = tableRef.value?.getSelectionRows();
  if (rows.length > 0) {
    rows.forEach((element: User) => {
      deleteClick(element, false);
    });
    getUsers();
    ElMessage.success("删除用户成功");
  } else {
    ElMessage.warning("请选择要删除的行");
  }
};

//分页功能
const pageChange = (page: number) => getUsers(pageParam.value);

//搜索功能
enum searchType {
  id = "id",
  userName = "userName",
  realName = "realName",
  sex = "sex",
  grade = "grade",
}

interface search {
  searchType: searchType;
  searchData: string | number;
}
const search = ref<search>({
  searchType: searchType.id,
  searchData: "",
});
const searchClick = async ({ searchType: type, searchData }: search) => {
  if (searchData) {
    let rows: PageResult<User[]> = { total: 0, rows: [] };
    switch (type) {
      case searchType.id:
        rows = {
          total: 1,
          rows: await UserAPI.searchById({ id: searchData as number }),
        };
        break;
      case searchType.userName:
        rows = await UserAPI.getUsers({ userName: searchData as string });
        break;
      case searchType.realName:
        rows = await UserAPI.getUsers({ realName: searchData as string });
        break;
      case searchType.sex:
        rows = await UserAPI.getUsers({ gender: searchData as 0 | 1 | 2 });
        break;
      case searchType.grade:
        rows = await UserAPI.getUsers({ grade: searchData as number });
        break;
    }
    updateUsers({ ...rows });
  } else {
    getUsers();
  }
  ElMessage.success("查询用户成功");
};
onMounted(() => getUsers());
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 15px;
}

.search {
  display: flex;
  justify-content: flex-end;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>
